<script lang="ts">
	import { Title, Content, Actions, InitialFocus } from '@smui/dialog';
	import Button, { Label } from '@smui/button';
	import { createEventDispatcher, onMount } from 'svelte';
	import { HelperLine } from '@smui/textfield';
	import { alova } from '$utils/request';
	import { createMessage } from '$components/basic/message';
	import HelperText from '@smui/textfield/helper-text';
	import Input from '$components/basic/input/Input.svelte';
	import { persistentWritable } from '$utils/persist';
	import { get } from 'svelte/store';
	import { validate_controller } from '$utils/validate';

	let open = false;

	export const openDialog = () => (open = true);

	let username = '';
	let password = '';
	let confirm = '';
	let verify_code = '';
	let clock = 0;

	const createTimeWaiting = (init = false) => {
		let time = persistentWritable<number>('forget:time', new Date().getTime());

		if (init) time.set(new Date().getTime());

		const animate = () =>
			requestAnimationFrame(() => {
				const cur = new Date().getTime();
				const record = get(time);
				if (record + 60 * 1000 > cur) {
					clock = 60 - Math.floor((cur - record) / 1000);

					animate();
				} else clock = 0;
			});

		animate();
		return time;
	};
	onMount(() => createTimeWaiting());

	const sendVerifyCode = async () => {
		if (clock > 0) return;
		createTimeWaiting(true);
		try {
			const res = (await alova.Post('/member/send-verify-code', {
				username,
				type: 0
			})) as API.ResOp;
			if (res.code === 0) createMessage({ message: res.message, type: 'danger' });
			else createMessage({ message: 'verify code send success', type: 'success' });
		} catch (error) {
			createMessage({ message: 'verify code send failed', type: 'danger' });
		}
	};

	const resetPassword = (params: CustomEvent) => {
		const createAction = (key: string) => () =>
			createMessage({ message: `${key} is required`, type: 'warning' });
		const controller = validate_controller();
		controller
			.put('email', username)
			.put('notnull', password, createAction('password'))
			.put('notnull', confirm, createAction('re-password'))
			.put('notnull', verify_code, createAction('verify code'));

		if (controller.check()) return;

		if (password.trim() !== confirm.trim()) {
			createMessage({ message: 'password not match', type: 'danger' });
			return (confirm = ''), (password = '');
		}

		alova
			.Post('/member/forget-password', { username, password, verify_code })
			.then((res) => {
				const { code, message } = res as API.ResOp;
				if (code === 0) createMessage({ message, type: 'danger' });
				else createMessage({ message, type: 'success' });
			})
			.catch((err) => {
				createMessage({ message: 'reset password failed', type: 'danger' });
			});
	};
</script>

<div class="login-wrapper h-full flex flex-row items-center gap-20px">
	<!-- Title cannot contain leading whitespace due to mdc-typography-baseline-top() -->
	<div class="min-w-1/2 h-fit flex flex-row-reverse pt-40px">
		<div class="w-700px h-fit p-20px shadow-2xl flex flex-col">
			<Title id="simple-title">Retrieve password</Title>
			<Content id="simple-content">
				<form>
					<div class="pl-20px flex flex-row items-center gap-10px">
						<div
							class="input-wrapper gap-10px flex flex-row items-center h-fit"
							style="width: 100%"
						>
							<Label for="username" class="w-120px">E-mail</Label>
							<div class="w-full flex grow-0.9 shrink-1 basis-0%">
								<Input type="text" name="username" class="w-full flex-1" bind:value={username} />
								<button
									class="relative flex-cc gap-10px color-gray-6 font-100"
									on:click={sendVerifyCode}
								>
									{#if clock}
										{clock}
									{/if}
									<span class="font-size-16px!">Get verification code</span>
								</button>
							</div>
						</div>
					</div>
					<div class="pl-20px flex flex-row items-center gap-10px">
						<Label for="Captcha" class="w-120px">Captcha</Label>
						<Input type="text" name="Captcha" style="flex: 0.9" bind:value={verify_code} />
					</div>
					<HelperLine class="ml-20px color-gray">
						<HelperText persistent={true}>
							{'Please check your email for the digital verification code.(Note: The code is valid for 10 mins)'}
						</HelperText>
					</HelperLine>
					<div class="pl-20px flex flex-row items-center gap-10px">
						<Label for="password" class="w-120px">Password</Label>
						<Input
							style="flex: 0.9"
							type="password"
							name="password"
							autocomplete="current-password"
							bind:value={password}
						/>
					</div>
					<div class="pl-20px flex flex-row items-center gap-10px">
						<Label for="confirm" class="w-120px">Re-password</Label>
						<Input style="flex: 0.9" type="text" name="confirm" bind:value={confirm} />
					</div>
					<HelperLine class="ml-20px color-gray">
						<HelperText persistent={true}>
							{'ConfirmNewPasswordTip'}
						</HelperText>
					</HelperLine>
				</form>
			</Content>
			<Actions class="flex flex-row justify-end">
				<Button
					on:click={resetPassword}
					variant="raised"
					style="--mdc-theme-primary: #ef4444"
					defaultAction
					use={[InitialFocus]}
				>
					<Label>submit</Label>
				</Button>
			</Actions>
		</div>
	</div>

	<div class="flex-1"></div>
</div>

<!-- <Button on:click={() => (open = true)}>
	<Label>Open Dialog</Label>
</Button> -->

<style lang="scss">
	.login-wrapper {
		/* background: #f0f0f0; */
		background-image: url('$lib/images/member-forget.svg');
		background-size: auto;
		background-repeat: no-repeat;
		background-position: right 20% bottom 0px;
	}

	button {
		border: 1px solid rgba(0, 0, 0, 0.36);
		padding-left: 18px;
		padding-right: 18px;
		height: 50px;
		outline-color: transparent;
		transition: outline-color 0.3s linear;
		background-color: #e2e8f0;

		&:focus {
			background-color: #f1f5f9;
		}

		&:active {
			background-color: #f1f5f9;
		}
	}
</style>
